///google.load("jquery", "1.4.1");
///HACK: OUTPUT FROM ESPN USES THESE METHOD CALLS. SO STUB THEM
var SHARETHIS = {
  addEntry: function(){
    return {
      attachButton: function(){}
    };
  }
};

gadgets.util.registerOnLoadHandler(function(){
  ;(function($) {
    // Initialize tabs, designate the tab named "NFL" as the tab selected by default.
    var prefs = new gadgets.Prefs();
    var tabs = new gadgets.TabSet(g_module_id, prefs.getString("selected_tab"));
    var view_params = gadgets.views.getParams();
    var entries = prefs.getInt("num_entries");
    var summaries = prefs.getBool("show_summ");
    var sports = {
      "Top": "espn",
      "Col Fball": "ncf",
      "NFL": "nfl",
      "MLB": "mlb",
      "NBA": "nba",
      "NHL": "nhl",
      "Col Hoops": "ncb"
    };
    
    function change_view(to,params) {
//      if(gadgets.views.getCurrentView().getName() != to) {
        gadgets.views.requestNavigateTo(new gadgets.views.View(to), params);
//      }
    };
    
    function make_cached_request(url, callback, params, refreshInterval) {
      var ts = new Date().getTime();
      var sep = "?";
      if (refreshInterval && refreshInterval > 0) {
        ts = Math.floor(ts / (refreshInterval * 1000));
      }
      if (url.indexOf("?") > -1) {
        sep = "&";
      }
      url = [ url, sep, "nocache=", ts ].join("");
      gadgets.io.makeRequest(url, callback, params);
    }
    
    function fetch_feed(tab_id) {
      var sport_name = tabs.getSelectedTab().getName();
      var sport = sports[sport_name];
      var params = {};
      var url = sport == "espn" ? "http://feeds.espn.go.com/nfl/widgets/s?c=news&a=feed&type=espn" : "http://feeds.espn.go.com/"+sport+"/widgets/s?c=news&a=feed";
      
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.FEED;  
      params[gadgets.io.RequestParameters.NUM_ENTRIES] = new Number(entries);  
      params[gadgets.io.RequestParameters.GET_SUMMARIES] = summaries; 
      
      prefs.set("selected_tab",sport_name);
      prefs.set("selected_sport",(sport == "espn" ? "" : sport));
      
      make_cached_request(url, response, params, 120);
    };
    
    function response(obj) {
      $(tabs.getSelectedTab().getContentContainer()).html(
        '<ul class="feedlist">'+$.map((obj.data.Entry||[]),function(item,i){
          return '<li><a target="_blank" href="'+item.Link+'" class="'+(item.Link.indexOf("story?id=") == - 1 ? "" : "expando")+'">'+item.Title+'</a>'+(summaries ? ('<br /><em>' + item.Summary.replace(/&#x26;#187;/g,'&#187;').replace(/a href/g,'a target="top" href') + '</em>') : '')+'</li>';
        }).join("")+'</ul>'
      );
      
      $(tabs.getSelectedTab().getContentContainer()).find("a").click(function(){
        if($(this).hasClass("expando")) {
          prefs.set("expando_url",$(this).attr('href'));
          change_view("canvas",{ url: $(this).attr('href') });
          return false;
        }
      });
      
      gadgets.window.adjustHeight();
    };
    
    function fetch_html(obj) {
      var header = $(obj.text).find(".mod-article-title").html();
      var body = $.map($(obj.text).find(".article>p:not([class])"),function(el){ return "<p>"+ $(el).html() + "</p>"; }).join("").replace(/<p><\/p>/,"");
      
      $("#content").html(header + body).append($('<a style="display:block;" href="#">Back to Headlines</a>').click(function(el){
        change_view("home");
        prefs.set("expando_url","");
        return false;
      }));
      $("#espnstlink").remove();
      $("a").attr("target","_blank");
      
      gadgets.window.adjustHeight();
    }
    
    if(gadgets.views.getCurrentView().getName().toLowerCase() == "home") {
      $("#content").hide();
      
      for(var i in sports){
        tabs.addTab(i, {
           contentContainer: document.getElementById(sports[i]),
           callback: fetch_feed
        });
      }
    } else {
      var params = {}; 
      
      if(!view_params.url) {
        view_params.url = (prefs.getString("expando_url") || $("a.expando:first").attr("href"));
      }
      
      $("#content").show();
      
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
      make_cached_request(view_params.url, fetch_html, params, 120);
    }
  })(jQuery);
});